const express = require('express');
const sendMail = require('../../utils/mail');
const { failure, success } = require('../../utils/responses');
const { User } = require('../../models');
const { NotFound, BadRequest } = require('http-errors');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { Op } = require('sequelize');
const { mailProducer } = require('../../utils/rabbit-mq');

router.post('/signIn', async (req, res) => {
  try {
    const { username, password, email, nickname, sex, introduce, avatar, company } = req.body;
    const user = await User.create({
      username,
      password,
      email,
      nickname,
      company,
      avatar,
      introduce,
      role: 0,
      sex: sex || 2,
    });
    // 将邮件发送请求放入队列
    const msg = {
      to: user.email,
      subject: '「长乐未央」的注册成功通知',
      html: `
          您好，<span style="color: red">${user.nickname}</span>。<br><br>
          恭喜，您已成功注册会员！<br><br>
          请访问<a href="https://miong.cn">「Miong」</a>官网，了解更多。<br><br>
          ━━━━━━━━━━━━━━━━<br>
          Miong
        `,
    };
    await mailProducer(msg);
    // 返回的数据里，要从user对象的dataValues中，delete掉密码字段，这是sequelize里的固定用法。
    delete user.dataValues.password; // 删除密码
    success({ res, message: '注册成功', code: 201, data: user });
  } catch (error) {
    failure({ error, res, message: '注册失败' });
  }
});

router.post('/login', async (req, res) => {
  try {
    const { username, email, password } = req.body;
    if (!username && !email) {
      throw BadRequest('请输入用户名或邮箱');
    }
    if (!password) {
      throw BadRequest('请输入密码');
    }

    const user = await User.findOne({
      where: { [Op.or]: [{ email: email || '' }, { username: username || '' }] },
    });
    if (!user) {
      throw new NotFound('用户不存在');
    }
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw BadRequest('密码错误');
    }

    const token = jwt.sign({ userId: user.id }, process.env.SECRET, {
      expiresIn: process.env.EXPIRES_TIME,
    });

    success({ res, message: '登录成功', code: 200, data: token });
  } catch (error) {
    failure({ error, res, message: '登录失败' });
  }
});
module.exports = router;
